using System;
using System.Data;
using MetaObjects.Contracts;

namespace MetaObjects.Core
{
	public class MetaDataColumn : IMetaField<DataRow, object>, IEntity<string>
	{
		object IEntity.Key { get { return InternalName; } }
		string IEntity<string>.Key { get { return InternalName; } }
		public string InternalName { get; private set; }
		public string DisplayName { get; set; }
		public string Description { get; set; }
		public bool Required { get; set; }
		public bool ReadOnly { get; set; }
		public object DefaultValue { get; set; }
		public Action<DataRow, object> SetField
		{
			get { return (row, value) => row[InternalName] = value ?? DBNull.Value;  }
		}
		public Func<DataRow, object> GetField
		{
			get { return row => row[InternalName] == DBNull.Value ? null : row[InternalName]; }
		}

		public MetaDataColumn(string internalName)
		{
			InternalName = internalName;
		}

		object IMetaField.DefaultValue
		{
			get { return DefaultValue; }
			set { DefaultValue = value; }
		}

		Action<object, object> IMetaField.SetField
		{
			get { return (row, value) => SetField((DataRow)row, value); }
		}

		Func<object, object> IMetaField.GetField
		{
			get { return row => GetField((DataRow)row); }
		}

		Action<object, object> IMetaField<object>.SetField
		{
			get { return (row, value) => SetField((DataRow)row, value); }
		}

		Func<object, object> IMetaField<object>.GetField
		{
			get { return row => GetField((DataRow)row); }
		}
	}
}